from moviepy.editor import VideoFileClip
from PIL import Image
import numpy as np
import os

def scale_with_black_bars(frame, target_size=(640, 480)):
    """保持宽高比缩放并添加黑边"""
    pil_img = Image.fromarray(frame)
    orig_width, orig_height = pil_img.size
    target_width, target_height = target_size
    
    # 计算缩放比例
    width_ratio = target_width / orig_width
    height_ratio = target_height / orig_height
    scale_ratio = min(width_ratio, height_ratio)
    
    # 计算新尺寸
    new_width = int(orig_width * scale_ratio)
    new_height = int(orig_height * scale_ratio)
    
    # 缩放图像
    resized = pil_img.resize((new_width, new_height), Image.LANCZOS)
    
    # 创建带黑边的目标图像
    result = Image.new("RGB", (target_width, target_height), (0, 0, 0))
    offset_x = (target_width - new_width) // 2
    offset_y = (target_height - new_height) // 2
    result.paste(resized, (offset_x, offset_y))
    
    return np.array(result)

def split_video(input_path, segment_duration=10):
    """分割视频并创建同名文本文件"""
    # 创建输出目录
    root_dir = os.path.split(input_path)[0]
    base_name = os.path.splitext(os.path.basename(input_path))[0]
    output_dir = os.path.join(root_dir,f"{base_name}_vidoe_splits")
    os.makedirs(output_dir, exist_ok=True)
    
    # 加载视频
    video = VideoFileClip(input_path)
    total_duration = video.duration
    segment_count = int(total_duration // segment_duration)
    
    # 处理每个分段
    for i in range(segment_count):
        start_time = i * segment_duration
        end_time = min((i + 1) * segment_duration, total_duration)
        
        # 跳过空分段
        if start_time >= total_duration:
            continue
        
        # 创建分段视频
        segment = video.subclip(start_time, end_time)
        
        # 应用缩放滤镜
        segment = segment.fl_image(lambda frame: scale_with_black_bars(frame))
        
        # 保存视频
        video_output = os.path.join(output_dir, f"{base_name}_part{i+1}.mp4")
        segment.write_videofile(video_output, codec="libx264", audio_codec="aac")
        
        # 创建同名文本文件
        txt_output = os.path.join(output_dir, f"{base_name}_part{i+1}.txt")
        with open(txt_output, "w") as f:
            f.write(f"Original video: {input_path}\n")
            f.write(f"Segment: {i+1}/{segment_count}\n")
            f.write(f"Start time: {start_time:.2f}s\n")
            f.write(f"End time: {end_time:.2f}s\n")
            f.write(f"Resolution: 640x480 (with black bars)\n")
        
        print(f"Created: {video_output} and {txt_output}")
    
    video.close()
    print(f"\nSuccessfully created {segment_count} segments in '{output_dir}'")

# 使用示例
if __name__ == "__main__":
    # 输入视频目录
    input_videos_dir = r"F:\回撤作业\回撤作业"
    input_videos = [os.path.join(input_videos_dir, f) for f in os.listdir(input_videos_dir) ]
    for input_video in input_videos:
        print(f"Processing: {input_video}")
        # 分割视频
        split_video(input_video)